package com.itstu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itstu.common.to.mq.SeckillOrderTo;
import com.itstu.common.utils.R;
import com.itstu.common.vo.MemberResponVo;
import com.itstu.gulimall.seckill.feign.CouponFeignService;
import com.itstu.gulimall.seckill.feign.ProductFeignService;
import com.itstu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.itstu.gulimall.seckill.service.SeckillService;
import com.itstu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.itstu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.itstu.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author shhjiang_001
 * @create 2020-06-04 21:44
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    SeckillService seckillService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";


    @Override
    public void uploadSeckillSkuLast3Days(){
        // 重复上架无需处理
        // 1. 扫描最近三天的秒杀活动
        R session = couponFeignService.getLast3DaysSession();
        if (session.getCode() == 0){
            if (session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {})!=null){
                // 上架商品
                List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
                });
                // 2. 缓存到redis
                //   1） 缓存活动信息
                saveSessionInfos(sessionData);
                //   2） 缓存活动商品信息
                saveSessionSkuInfos(sessionData);
            }else {
                System.out.println("最近三天没有秒杀商品");
            }

        }
    }

    /**
     * 获得当前参与秒杀的信息
     * @return
     */
    @Override
//    @SentinelResource(value = "getCurrentSeckillSkus")
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys){
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            long start = Long.parseLong(split[0]);
            long end = Long.parseLong(split[1]);
            if (/*time >= start &&*/ time <= end){
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<Object> list = hashOps.multiGet(range);
                if (list != null){
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redis = JSON.parseObject((String) item, SecKillSkuRedisTo.class);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        long s1 = System.currentTimeMillis();

        MemberResponVo memberResponVo = LoginUserInterceptor.loginUser.get();
        // 1. 获取当前商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if (!StringUtils.isEmpty(s)){
            SecKillSkuRedisTo redis = JSON.parseObject(s, SecKillSkuRedisTo.class);
            // 2. 校验时间
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = new Date().getTime();
            if (/*time >= startTime &&*/ time <= endTime ){
                // 3. 校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId()+ "_" + redis.getSkuId();
                if (key.equals(randomCode) && killId.equals(skuId)){
                    // 4. 验证商品数量
                    if (num <= redis.getSeckillLimit().intValue() ){
                        // 5. 验证该用户是否已经买过
                        String redisKey = memberResponVo.getId() + "_" + skuId;
                        // 自动过期
                        long ttl = endTime - time;
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MICROSECONDS);
                        if (ifAbsent){
                            // 站位成功
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE+key);
                                boolean b = semaphore.tryAcquire(num);
                                if (b){
                                    // 秒杀成功
                                    // 快速下单，发送MQ消息
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setNum(num);
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(memberResponVo.getId());
                                    orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    orderTo.setSkuId(redis.getSkuId());
                                    orderTo.setSeckillPrice(redis.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    long s2 = System.currentTimeMillis();
                                    log.info("耗费时间。。。。{}",s2-s1);
                                    return timeId;
                                }else {
                                    return null;
                                }
                        }else {
                            return null;
                        }

                    }else {
                        return null;
                    }
                }else {
                    return null;
                }

            }else {
                return null;
            }

        }else {
            return null;

        }
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX+startTime+"_"+endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey){
                List<String> collect = session.getRelationSkus().stream().map(item -> {
                    // TODO 活动信息的结构  key为活动前缀+起始时间  value为场次id+商品id
                    String s = item.getPromotionSessionId()+"_"+item.getSkuId();
                    return s;
                }).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
            // redis缓存活动信息，数据结果为 key为活动起始时间，value为活动的id
        });
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            // 准备hash操作 TODO 此处是否有重复操作，test验证一次  ? 经过验证当绑定hash的key值时，不会对redis数据库进行操作，
                    //  只有插入数据才会,此时这样做事最合理的。
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                Boolean hasKey = ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString());
                // 4. 设置随机码
                String token = UUID.randomUUID().toString().replace("-","");
                if (!hasKey){
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                    // 1. sku的基本数据
                    R skuInfo = productFeignService.info(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0){
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfoVo(info);
                    }
                    // 2. sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,redisTo);
                    // 3. 设置当前商品的秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    redisTo.setRandomCode(token);
                    String s = JSON.toJSONString(redisTo);
                    // TODO 活动商品信息的数据结构 key为秒杀信息前缀  hash-value为  K：秒杀场次id+商品id  V:商品信息
                    ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),s);
                    // 5. 使用库存作为分布式信号量，限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(Integer.parseInt(seckillSkuVo.getSeckillCount().toString()));
                }


            });
        });
    }

}
